//
//  ViewController.m
//  ABCDemoD
//
//  Created by Liu on 16/8/27.
//  Copyright © 2016年 Liu. All rights reserved.
//

#import "ViewController.h"
#import "ZLHistogramAudioPlot.h"
#import "GCDAsyncSocket.h"
#import "EZMicrophone.h"

@interface ViewController ()<ZLHistogramAudioPlotDelegate,GCDAsyncSocketDelegate>
{
    GCDAsyncSocket *asyncSocket;
}
@property (weak, nonatomic) IBOutlet UITextField *iptf; //ip
@property (weak, nonatomic) IBOutlet UITextField *porttf;  //port
- (IBAction)connect:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *state;

- (IBAction)sendMessage:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *dengdai1;
@property (weak, nonatomic) IBOutlet UITextField *dendai2;
@property (weak, nonatomic) IBOutlet UITextField *dengdai3;
@property (weak, nonatomic) IBOutlet UITextField *dengdai4;



@property (nonatomic, strong) ZLHistogramAudioPlot *audioPlot;

@property (nonatomic, strong) EZMicrophone *microphone;

@property (strong, nonatomic) NSArray *audioCopyColors;

@property (nonatomic, strong) NSMutableArray *mulDataArray;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _iptf.text = @"192.168.4.1";
    _porttf.text = @"222";
    _state.text = @"Disconnect";
    
    _dengdai1.text = @"255,0,0,10";
    
    
//    _mulDataArray = [[NSMutableArray alloc] init];
    
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    NSError *error;
//    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
//    if (error)
//    {
//        NSLog(@"Error setting up audio session category: %@", error.localizedDescription);
//    }
//    [session setActive:YES error:&error];
//    if (error)
//    {
//        NSLog(@"Error setting up audio session active: %@", error.localizedDescription);
//    }
//    
//    self.audioPlot = [[ZLHistogramAudioPlot alloc] init];
//    
//    self.audioPlot.backgroundColor =
//    [UIColor colorWithRed:0.984 green:0.71 blue:0.365 alpha:1];
    
//    self.audioPlot.plotType = EZPlotTypeBuffer;
//    // Fill
//    self.audioPlot.shouldFill = YES;
//    // Mirror
//    self.audioPlot.shouldMirror = YES;
//    
//    self.audioPlot.delegate = self;
//    
//
//     [self.microphone startFetchingAudio];
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- ZLHistogramAudioPlotDelegate



- (IBAction)connect:(id)sender {
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
    
    NSString *host = _iptf.text;
    uint16_t port = [_porttf.text integerValue];
    
    NSLog(@"Connecting to \"%@\" on port %hu...", host, port);
    
    NSError *error = nil;
    if (![asyncSocket connectToHost:host onPort:port error:&error])
    {
        NSLog(@"Error connecting: %@", error);
    }

}

#pragma mark ------ZLHistogramAudioPlotDelegate
- (void)updateDataMusic:(float *)heightsByFrequency numOfBins:(NSInteger)numOfBins {
    
    
//    
//    float led1 = 0;
//    float led2 = 0;
//    float led3 = 0;
//    float led4 = 0;
//    
//    int seper = numOfBins/4;
//    for (int i = 0; i<numOfBins; i++) {
//        if (i<seper) {
//            led1 += heightsByFrequency[i];
//        }else if (i<2*seper) {
//            led2 += heightsByFrequency[i];
//        }else if (i<3*seper) {
//            led3 += heightsByFrequency[i];
//        }else {
//            led4 += heightsByFrequency[i];
//        }
//    }
//    
//    
//    int ned1 = (int)led1%30;
//    int ned2 = (int)led2%30;
//    int ned3 = (int)led3%30;
//    int ned4 = (int)led4%30;
//    
//    ned1 = ned1>0?ned1:0;
//    ned2 = ned2>0?ned2:0;
//    ned3 = ned3>0?ned3:0;
//    ned4 = ned4>0?ned4:0;
//    
//    //    NSLog(@"A:%f--B:%f--C:%f--D:%f",led1,led2,led3,led4);
//    
////    int ranNumber = arc4random()%30;
//    ned1 = arc4random()%30;
//    ned2 = arc4random()%30;
//    ned3 = arc4random()%30;
//    ned4 = arc4random()%30;
//    
//    
//   
//    Byte b2[] = {'S','|',1,126,223,126,ned1,0,0,0,'|',2,122,98,67,ned2,0,0,0,'|',3,30,45,90,ned3,0,0,0,'|',4,231,124,23,ned4,0,0,0,'|','E'};
//    NSData *ColorData = [[NSData alloc] initWithBytes:b2 length:39];
//    
//    [asyncSocket writeData:ColorData withTimeout:1  tag:100];
//    
//    [self addDataToArray:ColorData];
}

- (void)addDataToArray:(NSData *)data {
    [self.mulDataArray addObject:data];
    
    
    
    
//    [asyncSocket writeData:ColorData withTimeout:30 tag:100];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}



#pragma mark Socket Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
    
    _state.text = @"Connected";
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socketDidDisconnect:%p withError: %@", sock, err);
    _state.text = @"Disconnected";
}



- (IBAction)sendMessage:(id)sender {
    
    NSString *dd1 = _dengdai1.text;
    NSString *dd2 = _dendai2.text;
    NSString *dd3 = _dengdai3.text;
    NSString *dd4 = _dengdai4.text;
    
    NSArray *ddA1 = [dd1 componentsSeparatedByString:@","];
    NSArray *ddA2 = [dd2 componentsSeparatedByString:@","];
    NSArray *ddA3 = [dd3 componentsSeparatedByString:@","];
    NSArray *ddA4 = [dd4 componentsSeparatedByString:@","];
    
    if (ddA1.count == 0 && ddA2.count == 0 && ddA3.count == 0 && ddA4.count == 0) {
        [self showError:@"请输入数据!"];
        return;
    }
    
    if ((dd1.length > 0 && ddA1.count != 4) ||
        (dd2.length > 0 && ddA2.count != 4) ||
        (dd3.length > 0 && ddA3.count != 4) ||
        (dd4.length > 0 && ddA4.count != 4)) {
        //data error
        [self showError:nil];
        return;
    }
    
    if (ddA1.count < 4) {
        ddA1 = @[@0,@0,@0,@0];
    }
    if (ddA2.count < 4) {
        ddA2 = @[@0,@0,@0,@0];
    }
    if (ddA3.count < 4) {
        ddA3 = @[@0,@0,@0,@0];
    }
    if (ddA4.count < 4) {
        ddA4 = @[@0,@0,@0,@0];
    }


    
    
    
    Byte b2[] = {'S','|',
        1,[ddA1[0] integerValue],[ddA1[1] integerValue],[ddA1[2] integerValue],[ddA1[3] integerValue],0,0,0,'|',
        2,[ddA2[0] integerValue],[ddA2[1] integerValue],[ddA2[2] integerValue],[ddA2[3] integerValue],0,0,0,'|',
        3,[ddA3[0] integerValue],[ddA3[1] integerValue],[ddA3[2] integerValue],[ddA3[3] integerValue],0,0,0,'|',
        4,[ddA4[0] integerValue],[ddA4[1] integerValue],[ddA4[2] integerValue],[ddA4[3] integerValue],0,0,0,'|','E'};
    NSData *sendData = [[NSData alloc] initWithBytes:b2 length:39];
    
    [asyncSocket writeData:sendData withTimeout:15  tag:100];
    
}

- (void)showError:(NSString *)message {
    if (message == nil) {
        message = @"错误的数据格式,请在每个输入框中按(r,g,b,n)的格式填写,()不算";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];

//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _dengdai1.text = @"255,0,0,10";
        _dendai2.text = @"";
        _dengdai3.text = @"";
        _dengdai4.text = @"";
    }];
//    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
